package com.onix.scalecamerapreview.translate;

import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.onix.scalecamerapreview.BuildConfig;

import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitUtil {
    private static Retrofit sRetrofit;
    private static OkHttpClient sOkHttpClient;
    private static RetrofitUtil instance;

    private final static Object mRetrofitLock = new Object();

    private static Retrofit getRetrofit() {
        if (sRetrofit == null) {
            synchronized (mRetrofitLock) {
                if (sRetrofit == null) {
                    sRetrofit = new Retrofit.Builder()
                            .client(getHttpClient())
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .baseUrl(Request.baseUrl)
                            .build();
                }
            }
        }
        return sRetrofit;
    }

    public static RetrofitUtil getInstance() {
        if (instance == null) {
            synchronized (RetrofitUtil.class) {
                if (instance == null) {
                    instance = new RetrofitUtil();
                }
            }
        }
        return instance;
    }




    public static OkHttpClient getHttpClient() {
        if (null == sOkHttpClient) {
            OkHttpClient.Builder builder;
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            if (BuildConfig.DEBUG) {
                builder = new OkHttpClient.Builder().addNetworkInterceptor(new StethoInterceptor());
                logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            } else {
                builder = new OkHttpClient.Builder();
                logging.setLevel(HttpLoggingInterceptor.Level.NONE);
            }
            sOkHttpClient = builder
                    .connectTimeout(25000, TimeUnit.MILLISECONDS)
                    .readTimeout(25000, TimeUnit.MILLISECONDS)
                    .writeTimeout(25000, TimeUnit.MILLISECONDS)
//                    .addInterceptor(new ErrorCodeInterceptor())
                    .addInterceptor(new HeadInterceptor())
                    .addInterceptor(logging)
                    .build();
        }
        return sOkHttpClient;
    }

    public <T> T get(Class<T> tClass) {
        return getRetrofit().create(tClass);
    }


}
